package com.feihao.zhou.controller;

import com.feihao.zhou.bean.Student;
import com.feihao.zhou.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    static StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        //获取前端请求：
        String option = req.getParameter("option");

        if ("login".equals(option)) {
            //是登录：跳到登录的方法：
            login(req, resp);
        } else if ("findStudent".equals(option)) {
            //是查询：跳到查询的方法：
            findStudent(req, resp);
        }
    }

    private void findStudent(HttpServletRequest req, HttpServletResponse resp) {


        try {
            String name = req.getParameter("name");
            String age = req.getParameter("age");

            List<Student> list = studentService.findStudent(name, age);

            req.setAttribute("studentList", list);
            req.getRequestDispatcher("/stu/show.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用service层：
        Boolean flag = studentService.CheckUser(username, password);

        if (flag) {
            //登录成功：设置登录信息到session域：
            req.getSession().setAttribute("username", username);
            //妆发到show.jsp:
            try {
                req.getRequestDispatcher("/stu/show.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                resp.sendRedirect("/login.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
